package io.chance.receiverlei.schedule;

import io.chance.receiverlei.db.DbManager;
import io.chance.receiverlei.db.model.MonitorDataDayModel;
import lrq.common.MyLog;
import lrq.data.DataTable;
import lrq.data.ParameterCollection;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class StatisticsDayData implements Job {

    Logger log = MyLog.getLogger(getClass().getSimpleName());

    @Override
    public void execute(JobExecutionContext arg0) throws JobExecutionException {

        try {
            log.info("开始统计天数据");
            Calendar cal = Calendar.getInstance();
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);

            Date startDate = cal.getTime();
            cal.add(Calendar.DAY_OF_MONTH, -1);
            Date endDate = cal.getTime();

//            String sql = " select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') QN,sys_guid() guid,'N' FLAG,? datatime,SITE_ID,avg(rtd) avg,max(rtd) max,min(rtd) min,DEVICETYPE from D_BC_SITE where datatime > ? and datatime < ? "
//                + " group by mn,DEVICETYPE ";
            String sql = " select to_char(sysdate,'YYYY-MM-DD HH24:MI:SS') QN,sys_guid() id,'N' FLAG,? datatime,SITE_ID,avg(rtd) avg,max(rtd) max,min(rtd) min,poll_code from D_BC_SITE where datatime > ?" +
                " " +
                "and datatime < ? "
                + " group by mn,poll_code ";
            ParameterCollection pc = new ParameterCollection();
            pc.add(startDate);
            pc.add(endDate);
            pc.add(startDate);

            DataTable table = DbManager.getDbExecuter().executeQuery(sql, pc);
            List<MonitorDataDayModel> models = table.toModels(MonitorDataDayModel.class);
            if (models != null && models.size() > 0) {
                DbManager.getDbExecuter().Create(models);
                log.info("天数据插入成功" + models.size());
            }
        }
        catch (Exception e) {
            log.error("统计天数据出错", e);
        }
    }
}
